package cn.yzx.pethome.system.dept.service.impl;

import cn.yzx.pethome.system.dept.domain.Department;
import cn.yzx.pethome.system.dept.domain.DepartmentBo;
import cn.yzx.pethome.system.dept.mapper.DepartmentMapper;
import cn.yzx.pethome.system.dept.service.IDepartmentService;
import cn.yzx.pethome.base.service.impl.BaseServiceImpl;
import cn.yzx.pethome.utils.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yzx
 * @since 2023-01-17
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public void delete(Long id) {
        Department depts = departmentMapper.findOne(id);
        if (depts.getState() == 0){
            departmentMapper.delete(id);
        }else {
            throw new BusinessException("请禁用后删除");
        }
    }

    @Override
    public List<Department> getDeptTree() {
        //找到全部
        List<Department> depts = departmentMapper.findAll();
        //创建部门树
        List<Department> deptTree = new ArrayList<>();
        //找最高部门
        for (Department dept : depts) {
            if (dept.getParentId() == null){
                deptTree.add(dept);
            }else {//去找子部门
                for (Department dept1 : depts){
                    if (dept.getParentId() == dept1.getId()){
                        dept1.getChildren().add(dept);
                    }
                }
            }
        }
        return deptTree;
    }

    @Override
    public List<DepartmentBo> countByEmp() {
        return departmentMapper.countByEmp();
    }

    @Override
    public void add(Department department) {
        //添加
        departmentMapper.add(department);
        getDirPath(department);
        departmentMapper.update(department);
    }

    @Override
    public void update(Department department) {
        if(department.getId().equals(department.getParentId())){
            throw new RuntimeException("不允许本部门为本部门上级部门");
        }
        getDirPath(department);
        departmentMapper.update(department);
    }

    private void getDirPath(Department department) {
        if (department.getParentId() == null){
            department.setDirPath("/" + department.getId());
        }else {
            Department parentDept = departmentMapper.findOne(department.getParentId());
            //获取上级部门的DirPath
            String dirPath = parentDept.getDirPath();
            //拼接
            department.setDirPath(dirPath +"/" + department.getId());
        }
    }
}
